import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/chat/chat_data.dart';
import 'package:flutter_app/chat/view_local_image.dart';
import 'package:flutter_app/paint/paint_board.dart';
import 'dart:async';

import 'package:flutter_app/water_fall/waterfall_stream.dart';
import 'package:image_picker/image_picker.dart';

List<String> chatDataSet = <String>[];
List<ChatData> chatDataSets = <ChatData>[]; //暂时没有用，不用改

///ChatData实体类，暂时没用
class ChatData {
  String belong; //聊天记录归属
  String message; //两天记录内容
  DateTime dateTime; //发送时间
  File file; //文件地址
  bool hasImage = false; //是否有图片，如果没有，且file不为空，就是文件
}

class SingleChat extends StatefulWidget {
  final String targetName;

  SingleChat(this.targetName);

  @override
  State<StatefulWidget> createState() {
    return SingleChatState(targetName);
  }
}

class SingleChatState extends State {
  final TextEditingController textEditingController = TextEditingController();
  final String targetName;
  final ScrollController _scrollController = new ScrollController();
  final FocusNode _focusNode = FocusNode();

  SingleChatState(this.targetName);

  File imageFile; //选择的媒体file
  bool choseImage; //是否已经选择了图片

  List<Chat_data> chat_data = new List<Chat_data>();
  List<String> image = new List<String>();

  addimage() {
    if (chat_data.elementAt(chat_data.length - 1).image != null) {
      image.add(chat_data.elementAt(chat_data.length - 1).image.path);
    }
  }

  @override
  void initState() {
    super.initState();
    choseImage = false;
    for (int i = 0; i < chat_data.length; i++) {
      if (chat_data.elementAt(i).image != null) {
        image.add(chat_data.elementAt(i).image.path);
      }
    }
    _Scroll();
  }

  _Scroll() {
    if (chat_data.length > 0)
      Timer(
          Duration(milliseconds: 500),
          () => _scrollController
              .jumpTo(_scrollController.position.maxScrollExtent));
  }

  _date() {
    DateTime now = new DateTime.now();
    String date = now.toString().substring(0, 19);
    // print(date.length);
    return date;
  }

  _pos(position){
    int pos=position;
    for(int i=0;i<position;i++){
      if(chat_data.elementAt(i).image==null){
        pos--;
      }
    }
    return pos;
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          leading: IconButton(
            icon: Icon(Icons.arrow_back),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
          centerTitle: true,
          title: Text(targetName),
          actions: <Widget>[
            IconButton(
                icon: Icon(Icons.view_stream),
                tooltip: "瀑布流",
                onPressed: () {
                  Navigator.of(context).push(MaterialPageRoute(
                      builder: (context) => WaterfallStream()));
                })
          ],
        ),
        body: Container(
          child: Column(
            children: <Widget>[
              Expanded(
                child: ListView.builder(
                  controller: _scrollController,
                  itemBuilder: (BuildContext context, int position) {
                    return Column(
                      children: <Widget>[
                        Text(
                          chat_data.elementAt(position).time,
                          style: TextStyle(fontSize: 10.0),
                        ),
                        Container(
                          margin: EdgeInsets.only(right: 15.0),
                          child: Row(
                            textDirection: TextDirection.rtl,
                            mainAxisAlignment:
                                chat_data.elementAt(position).isuser
                                    ? MainAxisAlignment.start
                                    : MainAxisAlignment.end,
                            children: <Widget>[
                              Container(
                                child: Icon(Icons.person, size: 40.0),
                                margin: EdgeInsets.fromLTRB(5.0, 0, 5.0, 0),
                              ),
                              Container(
                                decoration: BoxDecoration(
                                    border: Border.all(
                                        width: 3.0, color: Colors.black),
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(5.0))),
                                child: ConstrainedBox(
                                  constraints: BoxConstraints(
                                      maxWidth:
                                          MediaQuery.of(context).size.width *
                                              5 /
                                              7),
                                  child: Column(
                                    children: <Widget>[

                                    ],
                                  ),
                                ),
                              )
                            ],
                          ),
                        )
                      ],
                    );
                  },
                  itemCount: chat_data.length,
                ),
              ),
              Container(
                alignment: Alignment.bottomCenter,
                child: Column(
                  children: <Widget>[
                    Divider(),
                    Container(
                      margin: EdgeInsets.fromLTRB(12, 0, 12, 0),
                      child: Flex(
                        direction: Axis.horizontal,
                        children: <Widget>[
                          Expanded(
                            flex: 3,
                            child: Container(
                              height: 38,
                              margin: EdgeInsets.fromLTRB(0, 0, 12, 0),
                              child: TextField(
                                focusNode: _focusNode,
                                style: TextStyle(fontSize: 20.0),
                                controller: textEditingController,
                                decoration: InputDecoration(
                                  contentPadding:
                                      EdgeInsets.fromLTRB(12, 0, 12, 0),
                                  border: OutlineInputBorder(),
                                ),
                              ),
                            ),
                          ),
                          Expanded(
                            flex: 1,
                            child: FlatButton(
                              color: Colors.blue,
                              child: Text(
                                "发送",
                                style: TextStyle(color: Colors.white),
                              ),
                              onPressed: () {
                                if (textEditingController.text != '' ||
                                    imageFile != null) {
                                  //print(imageFile.path);
                                  setState(() {
                                    chat_data.add(new Chat_data(
                                        textEditingController.text,
                                        imageFile,
                                        true,
                                        _date()));
                                    addimage();
                                    choseImage = false; //发送后清零恢复图片选择状态
                                    imageFile = null;
                                    textEditingController.clear();
                                    _Scroll();
                                  });
                                }
                                //chatDataSet.add(textEditingController.text);
                              },
                            ),
                          )
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.fromLTRB(12, 0, 12, 0),
                      child: ButtonBar(
                        alignment: MainAxisAlignment.start,
                        children: <Widget>[
                          Container(
                            padding: EdgeInsets.fromLTRB(0, 0, 24, 6),
                            child: Tooltip(
                              message: "分享文件",
                              child: GestureDetector(
                                onTap: () {},
                                child: Icon(
                                  Icons.folder_shared,
                                  size: 28,
                                ),
                              ),
                            ),
                          ),
                          Container(
                            padding: EdgeInsets.fromLTRB(0, 0, 24, 6),
                            child: Tooltip(
                              preferBelow: false,
                              message: "插入图片",
                              child: GestureDetector(
                                onTap: () {
                                  getImage();
                                },
                                child: Icon(
                                  Icons.image,
                                  size: 28,
                                ),
                              ),
                            ),
                          ),
                          Container(
                            padding: EdgeInsets.fromLTRB(0, 0, 24, 6),
                            child: Tooltip(
                              message: "画图板",
                              child: GestureDetector(
                                onTap: () {
                                  Navigator.of(context).push(MaterialPageRoute(
                                      builder: (route) => PaintBoard()));
                                },
                                child: Icon(
                                  Icons.palette,
                                  size: 28,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    )
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  Future getImage() async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      if (imageFile != null) {
        setState(() {
          choseImage = true;
        });
      }
      imageFile = image;
    });
  }

  List<Widget> getChatDataList(int position){
    List widgets = [];
    if (chat_data.elementAt(position).text !=  null) {
      widgets.add(Text(
        chat_data
            .elementAt(position)
            .text,
        style: TextStyle(fontSize: 20.0),
        maxLines: null,
      ));
    }
    if (chat_data.elementAt(position).image != null){
      widgets.add(InkWell(
        child: Image(
          image: AssetImage(chat_data
              .elementAt(position)
              .image
              .path),
        ),
        onTap: () {
          Navigator.of(this.context).push(
              MaterialPageRoute(
                  builder: (route){
                    _focusNode.unfocus();
                    return ViewLocalImage(image, _pos(position));
                  }
              ));
        },
      ));
    }
    return widgets;
  }
}
